package cn.itsource.org.controller;

import cn.itsource.org.domain.Employee;
import cn.itsource.org.domain.Employee;
import cn.itsource.org.query.EmployeeQuery;
import cn.itsource.org.service.IEmployeeService;
import cn.itsource.org.service.IEmployeeService;
import cn.itsource.utils.AjaxResult;
import cn.itsource.utils.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController // 等价于  @Controller+@ResponseBody
@RequestMapping("/emp")
public class EmployeeController {


    @Autowired
    private IEmployeeService employeeService;

    @PutMapping
    public AjaxResult saveOrUpdate(@RequestBody Employee employee){
        try {
            if (employee.getId()!=null){
                employeeService.update(employee);
            }else {
                employeeService.save(employee);
            }
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage(e.getMessage());
        }

    }

    /*
        "/{id}"  在url里面有一个动态的占位符 名字id
        @PathVariable("id") 获取url里面的名字叫做id的占位符数据
     */
    //@RequestMapping(value = "/delete",method = RequestMethod.DELETE)
    @DeleteMapping("/{id}")
    public AjaxResult delete(@PathVariable("id") Long id){
        try {
            employeeService.delete(id);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage(e.getMessage());
        }

    }

    // @RequestMapping("/loadById")
    @GetMapping("/{id}")
    public Employee loadById(@PathVariable("id") Long id){
        try {
            return  employeeService.loadById(id);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    //@RequestMapping(value = "/loadAll",method = RequestMethod.GET)
    @GetMapping
    public List<Employee> loadAll(){
        try {
            return  employeeService.loadAll();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    //定义分页的方法
    @PostMapping
    public PageResult<Employee> queryPage(@RequestBody EmployeeQuery query){
        System.out.println(query);
        return employeeService.queryPage(query);
    }


    /*
        前台发送的数据：[10,12,14]

        后台接收数据：
            1.数组 Long[] ids
            2.集合
     */
    @PatchMapping
    public AjaxResult patchDelete(@RequestBody Long[] ids){
        try {
            employeeService.patchDelete(ids);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage(e.getMessage());
        }
    }

}
